package service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;



@WebServlet(urlPatterns = {"/list"})
public class DataService extends HttpServlet {
    private static final long serialVersionUID = 1L;

    static String[] prizeList = {"再接再厉","一等奖","二等奖","三等奖"};

    public static int writeData(String ip) throws SQLException {
        double result = Math.random();
        int prize;
        if(result < 0.125){
            prize = 1;
        }
        else if(result > 0.125 && result < 0.25){
            prize = 2;
        }
        else if(result > 0.25 && result < 0.375){
            prize = 3;
        }
        else{
            prize = 0;
        }
        SQLService.write(ip,prizeList[prize]);
        return prize;
    }

    public String readData() {
        String[][] res = SQLService.read();
        String out = "refresh,";
        for(int i = 0; i < 8; i++){
            out += res[i][0] + "," + res[i][1] + ",";
        }
        return out;
    }


    public DataService() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        try {
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setDateHeader("Expires", 0);
            String ip = request.getParameter("ip");
            out = response.getWriter();
            if(ip.equals("-1")){
                out.println(readData());
            }
            else{
                out.println(writeData(ip));
            }
        } catch (Exception e) {
            out.print("error: list");
            e.printStackTrace();
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}